package com.gpj.sqlbuilder.io;

import com.gpj.sqlbuilder.constants.Constants;
import com.gpj.sqlbuilder.utils.TextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;

/**
 * @className TemplateParser
 * @description
 *   模板解析器
 * @author GPJ
 * @date 2021/3/29 16:20
 * @version 1.0
 **/
@Slf4j
public class TemplateReader {
	private static final String NOTE_MARK = "//";

	public String read(InputStream io) {
		try (
				BufferedReader read = new BufferedReader(new InputStreamReader(io));
		){
			StringBuffer buffer = new StringBuffer();
			read.lines().forEach(line -> {
				line = line.trim();
				if(!line.startsWith(NOTE_MARK) && StringUtils.isNotBlank(line)){
					if(line.endsWith("+")){
						buffer.append(TextUtils.substr(0, -1, line));
					}else if(line.startsWith(Constants.TEMPLATE_START_MARK)
							|| line.endsWith(Constants.TEMPLATE_END_MARK)){
						buffer.append(line);
					}else{
						buffer.append(line).append(line.endsWith(Constants.ENTER_MARK) ? "" : Constants.ENTER_MARK);
					}
				}
			});
			return buffer.toString();
		} catch (IOException e) {
			log.error("模板读取失败:{}", e.getMessage());
		}
		return null;
	}
}
